<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Divide_model extends CI_Model {
	public function __construct() {
		parent::__construct ();
	}
	/*
	 * 根据分页信息返回拆分商品信息
	 */
	public function find_all_divides($per_page,$offset){
		$this->db->select('t_divide.id,producta.name as name1,producta.description as description1,productb.name as name2,productb.description as description2,amount');
		$this->db->from('t_divide');
		$this->db->join('t_product producta', 't_divide.productid = producta.id','left');
		$this->db->join('t_product productb', 't_divide.newproductid = productb.id','left');
		$this->db->limit($per_page, $offset);
		$this->db->order_by("id", "desc");
		$query = $this->db->get();
		return $query->result_array();
	}
	/*
	 * 返回拆分商品总数
	 */
	public function count_divides(){
		$query = $this->db->get('t_divide');
		return $query->num_rows();
	}
	/*
	 * 根据ID返回拆分商品信息
	 */
	public function load($id){
		$this->db->select('t_divide.id,t_divide.productid,t_divide.newproductid,producta.name as name1,productb.name as name2,t_divide.amount');
		$this->db->from('t_divide');
		$this->db->join('t_product producta', 't_divide.productid = producta.id','left');
		$this->db->join('t_product productb', 't_divide.newproductid = productb.id','left');
		$this->db->where('t_divide.id', $id);
		$query = $this->db->get();
		if ($row = $query->row_array()){
			return $row;
		}
		return array();
	}
	/*
	 * 添加拆分商品信息
	 */
	public function create($divide){
		$this->db->insert('t_divide', $divide);
		return $this->db->insert_id();
	}
	/*
	 * 更新拆分商品信息
	 */
	public function update($id,$divide){
		$this->db->where('id', $id);
		$this->db->update('t_divide', $divide);
		return $this->db->affected_rows()>0;
	}
	/*
	 * 删除拆分商品信息
	 */
	public function delete($id){
		$this->db->where('id', $id);
		$this->db->delete('t_divide');
		return $this->db->affected_rows()>0;
	}
	/*
	 * 根据newproductid得到拆分商品信息
	 */
	public function find_by_productid($newproductid){//
		$this->db->select('t_divide.productid,t_divide.amount,t_product.stock');
		$this->db->from('t_divide');
		$this->db->join('t_product', 't_divide.productid = t_product.id','left');
		$this->db->where('t_divide.newproductid', $newproductid);
		$query=$this->db->get();
		return $query->row_array();
	}
}